package com.itheima.tlias.filters;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.tlias.common.Result;
import com.itheima.tlias.utils.JwtUtils;
import io.jsonwebtoken.Claims;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 拦截器
 * @author
 * @version 1.0.1
 * @date 2023-04-11 11:08:44
 */
//@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //响应乱码

        //1.获取请求路径
        String uri = request.getRequestURI();    //  /login     共和国
        //StringBuffer url = request.getRequestURL();    //   http://localhost:8080/login   中华人民共和国
        //System.out.println("uri ->" + uri);
        //System.out.println("url ->" + url.toString());

        //2.判断请求路径是否为登录
        if(uri.contains("/login")) {
            //是：放行
            chain.doFilter(request, response);
            return;
        }
        response.setContentType("application/json;charset=UTF-8");
        ObjectMapper objectMapper = new ObjectMapper();
        //不是
        //3.获取token
        String token = request.getHeader("token");
        //4.判断token
        if(token == null || "".equals(token)) {
            //token为空，直接拦截，响应数据
            Result result = Result.error("token不能为空");
            String resultJson = objectMapper.writeValueAsString(result);
            //告知客户端，响应给你的是一个json
            response.getWriter().write(resultJson);
            return;
        }

        try {
            Claims claims = JwtUtils.parseJWT(token);
        } catch (Exception e) {
            e.printStackTrace();
            //token不为空，解析，解析失败，响应数据
            Result result = Result.error("token非法");
            String resultJson = objectMapper.writeValueAsString(result);
            //告知客户端，响应给你的是一个json
            response.getWriter().write(resultJson);
            return;
        }
        //放行
        chain.doFilter(request, response);
    }
}
